import { admin_login, find_password, getCode } from '@/services/login';
import { ProForm, ProFormCaptcha, ProFormInstance, ProFormText } from '@ant-design/pro-components';
import { history, Link, useModel } from '@umijs/max';
import { message, notification } from 'antd';
import CryptoJs from 'crypto-js';
import { useEffect, useRef, useState } from 'react';
import { flushSync } from 'react-dom';
import './index.less';
import globalKey from '@/utils/globalkey';

type Val = {
  phone: string;
  pwd: string;
  captcha?: string;
  password?: string;
  password_agn?: string;
};
const getLogin = () => {
  const formRef = useRef<ProFormInstance>();
  const [submitting, setSubmitting] = useState(false);
  const [type, setType] = useState('login');
  const { initialState, setInitialState } = useModel('@@initialState');

  useEffect(() => {
    notification.destroy(globalKey.sickbedWarningNotification)
  }, [])

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
    return userInfo;
  };
  // 点击登录
  const handleSubmit = async (values: Val) => {
    console.log(values);
    setSubmitting(true);
    try {
      // 登录
      const res: any = await admin_login({
        phone: values.phone,
        password: CryptoJs.MD5(values.pwd + 'f0c3c966').toString(),
        type: 1,
        origin: 'web',
      });
      console.log('1233', res);
      if (res.msg === 'ok') {
        const defaultloginSuccessMessage = '登录成功！';
        message.success(defaultloginSuccessMessage);
        localStorage.setItem('loginToken', res.data.tk);
        await fetchUserInfo();
        /** 此方法会跳转到 redirect 参数所在的位置 */
        const urlParams = new URL(window.location.href).searchParams;
        history.push(urlParams.get('redirect') || '/');
        return;
      } // 如果失败去设置用户错误信息
      message.error(res.msg);
      // message.error('手机号或密码错误');
    } catch (error) {
      const defaultloginFailureMessage = '登录失败，请重试！';
      message.error(defaultloginFailureMessage);
    }

    setSubmitting(false);
  };
  // 回车登录
  const keyUp = (e: { keyCode: number }) => {
    if (e.keyCode === 13) {
      //调用方法
      formRef.current?.validateFields().then((values) => {
        handleSubmit(values);
      });
    }
  };
  // 修改密码
  const changepassward = async (values: Val) => {
    console.log(values);
    if (values.password != values.password_agn) {
      message.error('填写的两个密码不相同');
      return false;
    }
    //组织数据
    let request_body = {
      //必填项
      phone: values.phone,
      code: values.captcha,
      password: CryptoJs.MD5(values.password + 'f0c3c966').toString(),
    };
    let res: any = await find_password(request_body);
    if (res.msg == 'ok') {
      //刷新列表
      message.success('修改成功');
      //关闭弹窗
      setInterval(() => {
        setType('login');
      }, 1000);
    } else {
      message.error(res.msg);
    }
  };
  return (
    <div className="container" onKeyUp={keyUp}>
      <div className="loginbox">
        <div className="content">
          <div className="main">
            {type === 'login' && (
              <>
                <div className="top">
                  <div className="header">
                    <Link to="/">
                      <img alt="logo" className="logo" src="/logo.png" />
                    </Link>
                  </div>
                  <div className="desc">康复管理中心</div>
                </div>
                <ProForm
                  formRef={formRef}
                  initialValues={
                    {
                      // autoLogin: true,
                    }
                  }
                  submitter={{
                    searchConfig: {
                      submitText: '登录',
                    },

                    render: (_, dom) => dom.pop(),
                    submitButtonProps: {
                      loading: submitting,
                      size: 'large',
                      style: {
                        width: '100%',
                      },
                    },
                  }}
                  onFinish={async (values: Val) => {
                    // setValue(values);
                    handleSubmit(values);
                    // console.log(values);
                  }}
                >
                  <ProFormText
                    name="phone"
                    fieldProps={{
                      size: 'large',
                    }}
                    placeholder="请输入手机号"
                    rules={[
                      {
                        required: true,
                        message: '请输入手机号!',
                        validateTrigger: 'onBlur',
                      },
                      {
                        pattern: /^1\d{10}$/,
                        message: '请输入正确的手机号',
                        validateTrigger: 'onBlur',
                      },
                    ]}
                  />
                  <ProFormText.Password
                    name="pwd"
                    fieldProps={{
                      size: 'large',
                    }}
                    placeholder="请输入密码"
                    rules={[
                      {
                        required: true,
                        message: '请输入密码',
                        validateTrigger: 'onBlur',
                      },
                    ]}
                  />
                </ProForm>
                <div className="btn-tips">
                  <a
                    onClick={() => {
                      setType('forgotpassword');
                    }}
                    style={{ cursor: 'pointer' }}
                  >
                    忘记密码
                  </a>
                </div>
              </>
            )}
            {type === 'forgotpassword' && (
              <>
                <div className="top">
                  <div className="desc-find">找回密码</div>
                </div>
                <ProForm
                  initialValues={
                    {
                      // autoLogin: true,
                    }
                  }
                  submitter={{
                    searchConfig: {
                      submitText: '确定',
                    },
                    render: (_, dom) => dom.pop(),
                    submitButtonProps: {
                      loading: submitting,
                      size: 'large',
                      style: {
                        width: '100%',
                      },
                    },
                  }}
                  onFinish={async (values: Val) => {
                    changepassward(values);
                  }}
                >
                  {/* {status === 'error' && (
              <LoginMessage
                content="账户或密码错误"
              />
            )} */}
                  <ProFormText
                    name="phone"
                    fieldProps={{
                      size: 'large',
                    }}
                    placeholder="请输入手机号"
                    rules={[
                      {
                        required: true,
                        message: '请输入手机号!',
                      },
                      {
                        pattern: /^1\d{10}$/,
                        message: '请输入正确的手机号',
                      },
                    ]}
                  />
                  <ProFormCaptcha
                    fieldProps={{
                      size: 'large',
                    }}
                    captchaProps={{
                      size: 'large',
                    }}
                    countDown={60}
                    placeholder="请输入验证码"
                    captchaTextRender={(timing, count) => {
                      if (timing) {
                        return `${count}秒后重新获取`;
                      }
                      return '获取验证码';
                    }}
                    phoneName="phone"
                    name="captcha"
                    rules={[
                      {
                        required: true,
                        message: '请输入验证码！',
                      },
                    ]}
                    onGetCaptcha={async (phone) => {
                      console.log(phone);
                      const result: any = await getCode({
                        phone,
                        type: 4,
                      });
                      console.log(result);
                      // console.log(phone)
                      if (result.msg === 'ok') {
                        message.success('获取验证码成功！');
                      } else {
                        message.error('验证码获取失败！');
                      }
                    }}
                  />
                  <ProFormText.Password
                    name="password"
                    fieldProps={{
                      size: 'large',
                      // prefix: <LockOutlined className="prefixIcon" />,
                    }}
                    placeholder="请输入新密码"
                    rules={[
                      {
                        required: true,
                        message: '请输入新密码',
                      },
                      {
                        pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,16}$/,
                        message: '密码必须是6-16位的字母加数字组合',
                      },
                    ]}
                  />
                  <ProFormText.Password
                    name="password_agn"
                    fieldProps={{
                      size: 'large',
                      // prefix: <LockOutlined className="prefixIcon" />,
                    }}
                    placeholder="再次输入密码"
                    rules={[
                      {
                        required: true,
                        message: '请再次输入密码！',
                      },
                      {
                        min: 6,
                        message: '密码最小6位',
                        validateTrigger: 'onBlur',
                      },
                      {
                        max: 16,
                        message: '密码最大16位',
                        validateTrigger: 'onBlur',
                      },
                    ]}
                  />
                </ProForm>
                <div className="btn-tips">
                  <a
                    onClick={() => {
                      setType('login');
                    }}
                    style={{ cursor: 'pointer' }}
                  >
                    立即登录
                  </a>
                </div>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};
export default getLogin;
